package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 苏成博
 * @date 2023-02-14 19:16
 */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 超时订单自动处理
     */
    @Scheduled(cron = "0 * * * * ? ")
    public void timeOutOrders() {
        log.info("超时订单处理");
        //处理超时订单15钟还未付款即视为超时
        //select * from orders where status=1 and order_time < LocalDateTime.now().plusMinutes(-15)
        List<Orders> ordersList = orderMapper.timeOutOrders(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-15));
        Orders orders;
        for (int i = 0; i < ordersList.size(); i++) {
            orders = ordersList.get(i);
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelReason("长时间未付款，自动取消");
            orders.setCancelTime(LocalDateTime.now());
            orderMapper.updateOrder(orders);
        }
    }

    /**
     * 已完成订单自动处理
     * 每日凌晨一点自动处理
     */
    @Scheduled(cron = "0 0 1 * * ? ")
    public void completeOrders(){
        log.info("已完成订单处理");
        List<Orders> ordersList = orderMapper.timeOutOrders(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().plusMinutes(-60));
        Orders orders;
        for (int i = 0; i < ordersList.size(); i++) {
            orders = ordersList.get(i);
            orders.setStatus(Orders.COMPLETED);
            orderMapper.updateOrder(orders);
        }
    }
}
